package me.android.library.utils.android.wifi;

import android.Manifest;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Build;

import androidx.annotation.RequiresApi;
import androidx.annotation.RequiresPermission;

import java.util.List;

import me.android.library.utils.android.SystemServiceUtil;
import mylab.utils.common.concurrent.Concurrent;

public interface WifiScanner {

    default WifiManager getWifiManager() {
        return SystemServiceUtil.getWifiManager();
    }

    List<ScanResult> getScanResult();

    @RequiresApi(api = Build.VERSION_CODES.R)
    default boolean startScan() {
        getWifiManager().registerScanResultsCallback(Concurrent.executor, getScanResultsCallback());
        return getWifiManager().startScan();
    }

    @RequiresApi(api = Build.VERSION_CODES.R)
    default void stopScan() {
        getWifiManager().unregisterScanResultsCallback(getScanResultsCallback());
    }

    @RequiresApi(api = Build.VERSION_CODES.R)
    default WifiManager.ScanResultsCallback getScanResultsCallback() {
        return new WifiManager.ScanResultsCallback() {
            @RequiresPermission(allOf = {Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.ACCESS_FINE_LOCATION})
            @Override
            public void onScanResultsAvailable() {
                getScanResult().clear();
                getScanResult().addAll(getWifiManager().getScanResults());
            }
        };
    }

}
